from invidious import *
import requests
import sys

from plugins.plugin import Plugin

sys.path.append("..")
from src.video import Video
from src.channel import Channel
from src.playlist import Playlist

from src.utils import *
from src.history import History
from src.config import Config

class InvidiousTrending(Plugin):

    def __init__(self, history: History=History(), config: Config=Config()) -> None:
        super().__init__(history, config)

        self.history = history
        self.config = config

        self.name = "[+] Invidious: Trending"
        self.category = "Invidious"

        self.query_description = """Please, input args (separate they with &) or leave this field empty.
    type: Music, Gaming, News, Movies (Ex: type=News)  
    region: your region (Ex: region=US)  

    Example: type=music&region=US    
"""

        self.params = {
            'query'     : True,
            'type'      : False,
            'region'    : False
        }

        self.flag = "-it"
        self.full_flag = "--ivtrending"
        self.flag_help = "show trending videos from invidious"
        self.flag_action = ""

    def get_trending(self, query: str=""):  
        dct = argstr_to_dict(query) 
        trending = self.invidious.get_trending(**dct)

        items = []
        for video in trending:
            if video == None: continue
            video.convert(Video)
            video.url = self.invidious.get_working_mirror() + "/watch?v=" + video.videoId
            inHistory = video.in_history(self.history)
            video.isWatched = inHistory
            item = video.to_json()
            items.append(item)

        return items

    def get_items(self, params):
        query = ""
        if 'query' in params:
            query = params['query']
        return self.get_trending(query=query)



